// set the dimensions and margins of the graph
const margin = { top: 100, right: 25, bottom: 30, left: 200 },
  heat_width = 750 - margin.left - margin.right,
  heat_height = 470 - margin.top - margin.bottom;

// append the svg object to the body of the page
const svg2 = d3
  .select("#heatmap")
  .append("svg")
  .attr("width", heat_width + margin.left + margin.right)
  .attr("height", heat_height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", `translate(${margin.left}, ${margin.top})`);

//Read the data
d3.csv("heat.csv").then(function (data) {
  // Labels of row and columns -> unique identifier of the column called 'group' and 'variable'
  const myGroups = Array.from(new Set(data.map((d) => d.group)));
  const myVars = Array.from(new Set(data.map((d) => d.variable)));

  // Build X scales and axis:
  const x = d3
    .scaleBand()
    .range([0, heat_width])
    .domain(myGroups)
    .padding(0.05);
  svg2
    .append("g")
    .style("font-size", 15)
    .attr("class", "xAxis")
    .attr("transform", "translate(0, -40)")
    //.attr("transform", `translate(0, ${height})`)
    .call(d3.axisBottom(x).tickSize(0))
    .select(".domain")
    .remove();

  svg2
    .selectAll(".xAxis .tick text")
    .attr("id", function (d, i) {
      // 根据索引分配不同的 ID
      if (i === 0) {
        return "overall";
      } else {
        return "category";
      }
    })
    .attr("dy", "0.5em") // Adjust vertical alignment
    .call(wrap, x.bandwidth()); // Call the wrap function with the bandwidth as an argument

  // Build Y scales and axis:
  const y = d3.scaleBand().range([heat_height, 0]).domain(myVars).padding(0.05);
  svg2
    .append("g")
    .attr("class", "yAxis")
    .style("font-size", 15)
    .call(d3.axisLeft(y).tickSize(0))
    .select(".domain")
    .remove();

  svg2
    .selectAll(".yAxis .tick text")
    .attr("id", "region")
    .attr("transform", "translate(-190,0)");

  // Function to wrap text
  function wrap(text, width) {
    text.each(function () {
      const text = d3.select(this);
      const words = text.text().split(/\s+/).reverse();
      let word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")) || 0,
        tspan = text
          .text(null)
          .append("tspan")
          .attr("x", 0)
          .attr("y", y)
          .attr("dy", dy + "em");

      while ((word = words.pop())) {
        line.push(word);
        tspan.text(line.join(" "));
        if (tspan.node().getComputedTextLength() > width) {
          line.pop();
          tspan.text(line.join(" "));
          line = [word];
          tspan = text
            .append("tspan")
            .attr("x", 0)
            .attr("y", y)
            .attr("dy", ++lineNumber * lineHeight + dy + "em")
            .text(word);
        }
      }
    });
  }

  // Build color scale
  const myColor = d3
    .scaleLinear()
    //.interpolator(d3.interpolateRgbBasis)
    .domain([100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0])
    .range([
      "#1368AA",
      "#4091C9",
      "#A2D2FF",
      "#BDE0FE",
      "#edf2fb",
      "#ffffff",
      "#FEC5BB",
      "#F7A399",
      "#F38375",
      "#F87575",
      "#F2545B",
    ]);

  // 创建图例
  const legendWidth = 400;
  const legendHeight = 20;
  const legend = d3
    .select("#heatmap") // 选择图例的容器，你可以根据实际情况选择合适的容器
    .append("svg")
    .attr("width", legendWidth)
    .attr("height", legendHeight);
  // .attr("transform", "translate(0,30)");

  // 创建渐变
  legend
    .append("defs")
    .append("linearGradient")
    .attr("id", "color-gradient")
    .selectAll("stop")
    .data(myColor.range().reverse())
    .enter()
    .append("stop")
    .attr("offset", (d, i) => i / (myColor.range().length - 1))
    .attr("stop-color", (d) => d);

  // 绘制渐变矩形
  legend
    .append("rect")
    .attr("width", legendWidth - 200)
    .attr("height", legendHeight)
    .attr("transform", "translate(85,0)")
    .style("stroke", "none")
    .style("fill", "url(#color-gradient)");

  legend
    .append("text")
    .attr("id", "heat-legend")
    .attr("transform", "translate(300, 15)") // 根据需要调整标签的位置
    .text("parity(100%)");
  legend
    .append("text")
    .attr("id", "heat-legend")
    .attr("transform", "translate(0, 15)") // 根据需要调整标签的位置
    .text("imparity(0%)");

  // add horizontal grid lines and a horizontal line at the top
  svg2
    .append("line")
    .attr("class", "top-line")
    .attr("x1", -margin.left)
    .attr("x2", heat_width - 4)
    .attr("y1", 0)
    .attr("y2", 0)
    .style("stroke", "#ccc")
    .style("stroke-width", 3);
  svg2
    .selectAll(".horizontal-line")
    .data(y.domain())
    .join("line")
    .attr("class", "horizontal-line")
    .attr("x1", -margin.left)
    .attr("x2", heat_width - 4)
    .attr("y1", function (d) {
      return y(d) + y.bandwidth() + 1;
    })
    .attr("y2", function (d) {
      return y(d) + y.bandwidth() + 1;
    })
    .style("stroke", "#ccc");

  // add vertical grid lines
  svg2
    .selectAll(".vertical-line")
    .data(x.domain())
    .join("line")
    .attr("class", "vertical-line")
    .attr("x1", function (d) {
      return x(d) - 2.5;
    })
    .attr("x2", function (d) {
      return x(d) - 2.5;
    })
    .attr("y1", 0)
    .attr("y2", heat_height)
    .style("stroke", "#ccc");

  // add the squares
  svg2
    .selectAll()
    .data(data, function (d) {
      return d.group + ":" + d.variable;
    })
    .join("rect")
    .attr("x", function (d) {
      return x(d.group);
    })
    .attr("y", function (d) {
      return y(d.variable);
    })
    //.attr("rx", 4)
    //.attr("ry", 4)
    .attr("width", x.bandwidth())
    .attr("height", y.bandwidth())
    .style("fill", function (d) {
      return myColor(+d.value);
    })
    .style("stroke-width", 4)
    .style("stroke", "none")
    .style("opacity", 0.8);

  // add text labels
  svg2
    .selectAll()
    .data(data, function (d) {
      return d.group + ":" + d.variable;
    })
    .join("text")
    .attr("x", function (d) {
      return x(d.group) + x.bandwidth() / 2;
    })
    .attr("y", function (d) {
      return y(d.variable) + y.bandwidth() / 2;
    })
    .attr("dy", "0.35em") // adjust the vertical alignment
    .style("text-anchor", "middle")
    .style("fill", "black") // set the text color
    .style("font-size", 12) // set the font size
    .text(function (d) {
      return d.value + "%"; // display the data value
    });
});

// Add title to graph
svg2
  .append("text")
  .attr("x", -201)
  .attr("y", -70)
  .attr("text-anchor", "left")
  .style("font-size", "22px")
  //.style("font-family", "sans-serif")
  .text(
    " regional performance across the four subindexes of gender gap index in 2022"
  );
